#include <webx/menu.h>

class GetFileList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetFileList)

int GetFileList::process()
{
	param_string(path);
	param_string(root);

	if (root.empty()) root = "/dat/pub";

	int res = 0;
	string sqlcmd;
	vector<string> vec;
	map<string, string> memap;
	string urlpath = root + "/" + path;
	string filepath = app->getPath() + urlpath.substr(1);

	webx::CheckFilePath(root, 0);
	webx::CheckFilePath(path, 0);

	if (path.length() > 0)
	{
		filepath += "/";
		urlpath += "/";
	}

	urlpath = stdx::replace(urlpath, "\\", "/");
	urlpath = stdx::replace(urlpath, "//", "/");

	stdx::GetFolderContent(vec, filepath);

	for (auto& item : vec)
	{
		sqlcmd += ",'" + urlpath + item + "'";
	}

	if (sqlcmd.length() > 0)
	{
		sqlcmd = "SELECT ID,REMARK FROM T_XG_FILE WHERE ID IN (" + sqlcmd.substr(1) + ")";

		sp<RowData> row;
		sp<DBConnect> dbconn = webx::GetDBConnect();
		sp<QueryResult> result = dbconn->query(sqlcmd);
		
		if (!result) return simpleResponse(XG_SYSBUSY);

		while (row = result->next())
		{
			memap[row->getString(0)] = row->getString(1);
		}
	}

	JsonElement arr = json.addArray("list");

	for (auto& item : vec)
	{
		string url = urlpath + item;
		string path = filepath + item;
		string link = stdx::EncodeURL(url);

		JsonElement data = arr[res++];
		const long size = path::size(path);
		const time_t utime = path::mtime(path);

		if (size < 0)
		{
			data["icon"] = "/res/img/menu/folder.png";
			data["type"] = (int)(0);
			data["size"] = (int)(0);
		}
		else
		{
			data["icon"] = webx::GetFileIcon(item);
			data["type"] = (int)(1);
			data["size"] = size;
			
			if (size < 256 * 1024)
			{
				string extname = stdx::tolower(path::extname(item));

				if (extname == "jpg" || extname == "png" || extname == "gif" || extname == "jpeg")
				{
					data["icon"] = link + "?utime=" + stdx::str(utime);
				}
			}
		}

		data["url"] = link;
		data["name"] = item;
		data["remark"] = memap[url];
		data["datetime"] = utime ? DateTime(utime).toString() : stdx::EmptyString();
	}

	try
	{
		checkLogin();
		checkSystemRight();

		json["system"] = (int)(1);
	}
	catch(Exception e)
	{
		json["system"] = (int)(0);
	}

	json["path"] = path;
	json["code"] = res;
	out << json;

	return XG_OK;
}